package com.gzw.scm.activity;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.support.v7.widget.CardView;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.google.gson.reflect.TypeToken;
import com.gzw.scm.DEL.DBManager;
import com.gzw.scm.MyApplication;
import com.gzw.scm.R;
import com.gzw.scm.adapter.ZZXFPAdapter;
import com.gzw.scm.base.BaseActivity;
import com.gzw.scm.bean.Constant;
import com.gzw.scm.utils.HttpUtils;
import com.gzw.scm.utils.JsonUtil;
import com.gzw.scm.utils.T;
import com.gzw.scm.utils.UrlUtils;
import com.gzw.scm.view.SwipeRefreshLayout;

import org.apache.log4j.Logger;

import java.util.ArrayList;
import java.util.List;
import static com.gzw.scm.bean.Constant.USERINFO_KEY;


/**
 * Created by Administrator on 2017/8/8.
 */

public class JSZZXActivity extends BaseActivity{
    private Context mContext;
    private RecyclerView mRecyclerView;
    private Button btn_sure,btn_delete;
    private TextView tv_seleteAll,tv_sl;
    private boolean isCheck = false;
    private DBManager dbManager;
    private List<String> ls_bh,ls_xzbh;
    private ZZXFPAdapter zzxfpAdapter;
    private ProgressDialog mProgressDialog;
    private SwipeRefreshLayout mSwipeLayout;
    private String dataType ;
    private Toolbar toolbar;
    private android.support.v7.widget.CardView cardView;
    private List<String> lsbh;
    private Logger log;

    @Override
    protected void setContentView() {
        setContentView(R.layout.activity_newzcjs);
    }

    @Override
    protected void initViews() {
        toolbar = (Toolbar)findViewById(R.id.toolbar);
        mRecyclerView = (RecyclerView) findViewById(R.id.rv_fp);
        btn_sure = (Button)findViewById(R.id.btn_sure);
        btn_delete = (Button)findViewById(R.id.btn_delete);
        tv_seleteAll = (TextView) findViewById(R.id.ic_head1).findViewById(R.id.tv_selectAll);
        cardView =(CardView)findViewById(R.id.cv_sl);
        tv_sl=(TextView)findViewById(R.id.tv_sl);

        //初始化 log
        log=Logger.getLogger(this.getClass());
    }

    @Override
    protected void initData() {
        mContext = this;
        cardView.setVisibility(View.GONE);

        if(readly().equals("1")){
            dataType="rdczxjs";
            toolbar.setTitle("正向接收");

            GetSLTask getSLTask = new GetSLTask();
            getSLTask.execute();

        }else if(readly().equals("2")){
            dataType="rdcnxjs";
            toolbar.setTitle("逆向接收");

//            GetNXSLTask getNXSLTask = new GetNXSLTask();
//            getNXSLTask.execute();
        }
         setSupportActionBar(toolbar);

        /**
        * 刷新框架
        * */
        mRecyclerView.setHasFixedSize(true);
        //设置布局管理器
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        //设置Item增加、移除动画
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        //添加默认分割线
        mSwipeLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);

        mSwipeLayout.setColor(android.R.color.holo_blue_bright,
                android.R.color.holo_green_light,
                android.R.color.holo_orange_light,
                android.R.color.holo_red_light);
        mSwipeLayout.setMode(SwipeRefreshLayout.Mode.DISABLED);
        mSwipeLayout.setLoadNoFull(false);

        dbManager=new DBManager(mContext);
        ls_bh= new ArrayList<>();
        ls_xzbh = new ArrayList<>();
        lsbh=new ArrayList<>();
        setData();
    }

    @Override
    protected void initEvents() {
        toolbar.setNavigationOnClickListener(new myOnClick());
        btn_sure.setOnClickListener(new myOnClick());
        btn_delete.setOnClickListener(new myOnClick());
        tv_seleteAll.setOnClickListener(new myOnClick());
    }

    class myOnClick implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            switch (v.getId()) {
                case R.id.btn_sure:
                    senddata();
                    break;
                case R.id.btn_delete:
                    deleteZzxbh();
                    break;
                case R.id.tv_selectAll:
                    if (ls_bh != null) {
                        if (isCheck == false) {
                            // 遍历list的长度，将MyAdapter中的map值全部设为true
                            for (int i = 0; i < ls_bh.size(); i++) {
                                zzxfpAdapter.getIsSelected().put(i, true);
                            }
                            zzxfpAdapter.notifyDataSetChanged();
                            //改变状态
                            isCheck = true;
                        } else {
                            // 遍历list的长度，将已选的按钮设为未选
                            for (int i = 0; i < ls_bh.size(); i++) {
                                if (ZZXFPAdapter.getIsSelected().get(i)) {
                                    ZZXFPAdapter.getIsSelected().put(i, false);
                                }
                            }
                            zzxfpAdapter.notifyDataSetChanged();
                            isCheck = false;
                        }
                    }
                    break;
                default:
                    finish();
                    break;
            }
        }
    }

    /**
     * 扫描结果
     * */
    protected String scanRelust(String code){
        if(code.equals("该二维码不是周转箱")){
            T.showShort(mContext,"该二维码不是周转箱");
        }else{
            isScan(code);
        }
        return code;
    }

    /**
     * 判断是否已扫
     * */
    private void isScan(String bh){
        Boolean isExist = dbManager.IsExistZzxbh(bh,dataType, MyApplication.getUserInfo().getDid());
        if(isExist){
            T.showShort(mContext,"该二维码已扫描");
        }else{
            dbManager.addZzxbh(bh,dataType,MyApplication.getUserInfo().getDid());
            setData();
        }
    }

    /**
     * 列表赋值
     * */
    private void setData(){
        ls_bh.clear();
        List<String> lsbh=dbManager.selectFPZzxbh(dataType,MyApplication.getUserInfo().getDid());
        if(lsbh==null){
            return;
        }else {
            ls_bh.addAll(lsbh);
        }
        if(ls_bh==null){
            return;
        }
        zzxfpAdapter = new ZZXFPAdapter(ls_bh);
        mRecyclerView.setAdapter(zzxfpAdapter);

        zzxfpAdapter.setOnRecyclerViewListener(new ZZXFPAdapter.OnRecyclerViewListener() {
            @Override
            public void onItemClick(int position) {
                if(ZZXFPAdapter.getIsSelected().get(position)==true){
                    ZZXFPAdapter.getIsSelected().put(position, false);
                    zzxfpAdapter.notifyDataSetChanged();
                }else{
                    ZZXFPAdapter.getIsSelected().put(position, true);
                    zzxfpAdapter.notifyDataSetChanged();
                }
            }
            @Override
            public boolean onItemLongClick(int position) {
                return false;
            }
        });

    }

    /**
     * 删除周转箱编号
     * */
    private void deleteZzxbh(){
         lsbh.clear();
        for (int i = 0; i < ls_bh.size(); i++) {
            if (zzxfpAdapter.getIsSelected().get(i)) {
                lsbh.add(ls_bh.get(i));
            }
        }
        if(lsbh.size()==0){
            T.showShort(mContext,"请先选择要删除的编号!");
        }else {
            showDeleteInfo(lsbh);
        }
    }

    /**
     * 删除数据是的提示框
     * */
    private void showDeleteInfo(final List<String> ls_bh){
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("确定要删除这"+ls_bh.size()+"个编号吗?");
        builder.setPositiveButton("确定", (dialog, which) -> {
                dbManager.deleteFPZzxbh(ls_bh,dataType,MyApplication.getUserInfo().getDid());
                setData();
        });
        builder.setNegativeButton("取消", (dialog, which) -> {
        });
        builder.show();
    }

    /**
     * 上传数据
     * */
    private void senddata(){
        lsbh.clear();
        for (int i = 0; i < ls_bh.size(); i++) {
            if (zzxfpAdapter.getIsSelected().get(i)) {
                lsbh.add(ls_bh.get(i));
            }
        }
        if(lsbh.size()==0){
            T.showShort(mContext,"请先选择要分配的编号!");
        }else {
            showSendInfo(lsbh);
        }
    }

    /**
     * 删除数据是的提示框
     * */
    private void showSendInfo(final List<String> ls_bh){
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("确定要接收这"+ls_bh.size()+"个周转箱吗?");
        builder.setPositiveButton("确定", (dialog, which) -> {
                ls_xzbh.clear();
                ls_xzbh.addAll(ls_bh);
                String idStr=new String();
                for (String str:ls_bh){
                    idStr=idStr+str+",";
                }
                idStr = idStr.substring(0, (idStr.length()-1));

                if(readly().equals("1")){
                    ZXJSTask zxjsTask = new ZXJSTask();
                    zxjsTask.execute(idStr);
                }else if(readly().equals("2")){
                    NXJSTask nxjsTask = new NXJSTask();
                    nxjsTask.execute(idStr);
                }
        });
        builder.setNegativeButton("取消", (dialog, which) -> {
        });
        builder.show();
    }

    /**
     * 上传的数据请求
     * RDC正向接收
     * */

    public class ZXJSTask  extends AsyncTask<String, Void, String> {
        //onPreExecute方法用于在执行后台任务前做一些UI操作
        @Override
        protected void onPreExecute() {
            mProgressDialog = ProgressDialog.show(mContext, null, "正在加载中...");
            mProgressDialog.setCancelable(true);
        }

        protected String doInBackground(String... params) {
            SharedPreferences sharedPreferences = getSharedPreferences(USERINFO_KEY, Context.MODE_PRIVATE);
            String userId = String.valueOf(sharedPreferences.getInt(Constant.UAER_ID,00000000000));
            String department_name = sharedPreferences.getString(Constant.DEPARTMENT_NAME, null);
            String json="peoid="+userId +"&rdcid="+MyApplication.getUserInfo().getDid()+"&tboxno="+params[0]
                    +"&didname="+department_name+"&address=山东"+"&belongid="+String.valueOf(MyApplication.getUserInfo().getBelongId());
            return HttpUtils.doPost(UrlUtils.getInstance().getNewJavaUrl("rdcpda.do", "ZZreceive"),json);
        }

        @Override
        protected void onPostExecute(final String result) {
            mProgressDialog.dismiss();
          try{
            if (result == null || result.length() == 0) {
                showAlertDialog("连接异常");
                return;
            }
            if(result.contains("true")){
                showAlertDialog("接收成功"+lsbh.size()+"个周转箱");
                dbManager.deleteFPZzxbh(ls_xzbh,dataType,MyApplication.getUserInfo().getDid());
                setData();
            }else if(result.contains("系统异常")){
                showAlertDialog("网络异常");
            }else if(result.contains("all")){
                String all = JsonUtil.getMsg(result,"order")
                        .toString();
                String alldh = JsonUtil.getMsg(all,"all")
                        .toString();
                showAlertDialog(alldh+"不符合接收条件");
            }else if(result.contains("yijieshou")||result.contains("other")){
                  String order = JsonUtil.getMsg(result,"order")
                          .toString();

                  String dh = JsonUtil.getMsg(order,"yijieshou")
                          .toString();
                  String dh1 = JsonUtil.getMsg(order,"other")
                          .toString();

                  List<String> ls_dh = JsonUtil.getPersons(dh, new TypeToken<List<String>>() {
                  }.getType());

                  List<String> ls_dh1 = JsonUtil.getPersons(dh1, new TypeToken<List<String>>() {
                  }.getType());


                  ls_xzbh.removeAll(ls_dh);
                  ls_xzbh.removeAll(ls_dh1);

                  dbManager.deleteFPZzxbh(ls_xzbh,dataType,MyApplication.getUserInfo().getDid());
                  setData();

                  String str1="",str2="";
                  if(ls_dh.size()!=0){
                      str1="周转箱"+dh+"已接收";
                  }
                  if(ls_dh1.size()!=0){
                      str2="周转箱"+dh1+"不属于本本部门";
                  }
                  showAlertDialog("接收成功"+ls_xzbh.size()+"个周转箱"+"    "+str1+str2);
              }else{
                showAlertDialog(result);
            }
          }catch (Exception e) {
              log.info("ZZreceive:"+e.toString()+"/result="+result);
              e.printStackTrace();
              showAlertDialog(e.toString());
          }
        }
    }

    /**
     * 上传的数据请求
     * RDC逆向向接收
     * */
    public class NXJSTask  extends AsyncTask<String, Void, String> {
        //onPreExecute方法用于在执行后台任务前做一些UI操作
        @Override
        protected void onPreExecute() {
            mProgressDialog = ProgressDialog.show(mContext, null, "正在加载中...");
            mProgressDialog.setCancelable(true);
        }

        protected String doInBackground(String... params) {
            String json="peoid="+MyApplication.getUserInfo().getId()
                    +"&nowdid="+MyApplication.getUserInfo().getDid()+"&tboxno="+params[0]
                    +"&didname="+MyApplication.getUserInfo().getDepartment_name()+"&address=山东"
                    +"&belongid="+String.valueOf(MyApplication.getUserInfo().getBelongId());
            return HttpUtils.doPost(UrlUtils.getInstance().getNewJavaUrl("rdcpda.do", "NZreceive"),json);
        }

        @Override
        protected void onPostExecute(final String result) {
            mProgressDialog.dismiss();
            try{
            if (result == null || result.length() == 0) {
                showAlertDialog("连接异常");
                return;
            }
            if(result.contains("true")){
                showAlertDialog("接收成功"+lsbh.size()+"个周转箱");
                dbManager.deleteFPZzxbh(ls_xzbh,dataType,MyApplication.getUserInfo().getDid());
                setData();
            }else if(result.contains("系统异常")){
                showAlertDialog("网络异常");
            }else if(result.contains("order")){
                String dh = JsonUtil.getMsg(result,"order")
                        .toString();

                if(dh.equals("false")){
                    showAlertDialog("逆向接收失败");
                    return;
                }else {
                    String[] str_Array = dh.split(",");
                    List<String> ls = new ArrayList<>();
                    for (int i = 0; i < str_Array.length; i++) {
                        ls.add(str_Array[i]);
                    }
                    ls_xzbh.removeAll(ls);
                    dbManager.deleteFPZzxbh(ls_xzbh, dataType, MyApplication.getUserInfo().getDid());
                    setData();
                    showAlertDialog("接收成功" + ls_xzbh.size() + "个周转箱," + dh + "不属于本部门或已经接收");
                }
            }else{
                showAlertDialog(result);
            }
            }catch (Exception e) {
                log.info("NZreceive:"+e.toString()+"/result="+result);
                e.printStackTrace();
                showAlertDialog(e.toString());
            }
        }
    }

    /**
     * 正向接收待接收的数据请求
     */

    public class GetSLTask extends AsyncTask<String, Void, String> {
        //onPreExecute方法用于在执行后台任务前做一些UI操作
        @Override
        protected void onPreExecute() {
            mProgressDialog = ProgressDialog.show(mContext, null, "正在加载中...");
            mProgressDialog.setCancelable(true);
        }

        protected String doInBackground(String... params) {
            String json="rdcid="+ MyApplication.getUserInfo().getDid();
            return HttpUtils.doPost(UrlUtils.getInstance().getNewJavaUrl("rdcpda.do","Count"),json);
        }

        @Override
        protected void onPostExecute(final String result) {
            mProgressDialog.dismiss();
            try{
            if (result == null || result.length() == 0) {
                showAlertDialog("连接异常");
                return;
            }
                if(result.contains("系统异常")){
                    showAlertDialog("网络异常");
                    return;
                }
            String order = JsonUtil.getMsg(result,"order").toString();
            if(order.equals("false")){
                showAlertDialog("未查询出待接收数量");
            }else if(order.equals("true")){
                String count = JsonUtil.getMsg(result,"count").toString();
                cardView.setVisibility(View.VISIBLE);
                tv_sl.setText(count);
            }
            }catch (Exception e) {
                log.info("Count:"+e.toString()+"/result="+result);
                e.printStackTrace();
                showAlertDialog(e.toString());
            }
        }
    }

    /**
     * 逆向接收待接收的数据请求
     */

    public class GetNXSLTask extends AsyncTask<String, Void, String> {
        //onPreExecute方法用于在执行后台任务前做一些UI操作
        @Override
        protected void onPreExecute() {
            mProgressDialog = ProgressDialog.show(mContext, null, "正在加载中...");
            mProgressDialog.setCancelable(true);
        }

        protected String doInBackground(String... params) {
            String json="did="+ MyApplication.getUserInfo().getDid();
            return HttpUtils.doPost(UrlUtils.getInstance().getNewJavaUrl("rdcpda.do","NiCount"),json);
        }

        @Override
        protected void onPostExecute(final String result) {
            mProgressDialog.dismiss();
            try{
                if (result == null || result.length() == 0) {
                    showAlertDialog("连接异常");
                    return;
                }
                if(result.contains("系统异常")){
                    showAlertDialog("网络异常");
                    return;
                }
                if(result.contains("str")){
                    String str = JsonUtil.getMsg(result,"str").toString();
                    cardView.setVisibility(View.VISIBLE);
                    tv_sl.setText(str);
                }else if(result.contains("err")){
                    showAlertDialog("未查询出待接收数量");
                }else{
                    showAlertDialog(result);
                }
            }catch (Exception e) {
                log.info("Count:"+e.toString()+"/result="+result);
                e.printStackTrace();
                showAlertDialog(e.toString());
            }
        }
    }

    private String readly() {
        SharedPreferences sharedPreferences = mContext.getSharedPreferences(USERINFO_KEY,
                Context.MODE_PRIVATE);
        String ly = sharedPreferences.getString("ly","");
        return ly;
    }

}